package com.zclcs.config;

import java.util.HashSet;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

import com.zclcs.model.User;
import com.zclcs.service.UserService;
import com.zclcs.utils.ServletContextUtil;

/**
 * 登录处理
 * 
 * @author 周成龙
 *
 */
public class MyShiroRealm extends AuthorizingRealm {

	@Autowired
	@Lazy
	private UserService userService;

	public MyShiroRealm(CacheManager cacheManager, CredentialsMatcher matcher) {
		super(cacheManager, matcher);
	}

	/**
	 * 获取权限 - 鉴权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

		// 权限信息对象info,用来存放查出的用户的所有的角色（role）及权限（permission） SimpleAuthorizationInfo
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		// 用户的角色集合
		// Set<String> roles = new HashSet<>();
		// 用户的角色集合
		Set<String> permissions = new HashSet<>();
		String[] userPermissions = ServletContextUtil.getUserInfo().getRoles();
		for (int i = 0; i < userPermissions.length; i++) {
			permissions.add(userPermissions[i]);
		}
		authorizationInfo.setStringPermissions(permissions);
		return authorizationInfo;

	}

	/**
	 * 主要是用来进行身份认证的，也就是说验证用户输入的账号和密码是否正确。
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		// 获取用户的输入的账号.
		String username = (String) token.getPrincipal();
		// 通过username从数据库中查找 User对象，如果找到，没找到.
		// 实际项目中，这里可以根据实际情况做缓存，如果不做，Shiro自己也是有时间间隔机制，2分钟内不会重复执行该方法
		User user = userService.findByUsername(username);
		// Subject subject = SecurityUtils.getSubject();
		// Session session = subject.getSession();
		// session.setAttribute("role",userInfo.getRoleList());
		// System.out.println("----->>userInfo="+userInfo);
		if (user == null) {
			return null;
		}
		String credentials = user.getPassword();
		ByteSource credentialsSalt = ByteSource.Util.bytes(username);
		SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user.getUsername(), // 用户名
				credentials, // 密码
				credentialsSalt, getName() // realm name
		);
		return authenticationInfo;
	}
}